package com.app.micaihu.view.main.mine.fragment;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.app.base.BaseFragment;
import com.app.micaihu.R;
import com.app.micaihu.bean.infor.UserInfor;
import com.app.micaihu.bean.infor.UserTask;
import com.app.micaihu.bean.message.MineSetList;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.ConfigKeyConstant;
import com.app.micaihu.configure.TypeConstant;
import com.app.micaihu.custom.view.CustomImageView;
import com.app.micaihu.manager.AppConfigManager;
import com.app.micaihu.manager.UserInforManager;
import com.app.micaihu.utils.ImageLoadUtils;
import com.app.micaihu.view.army.activity.ArmyMedalListActivity;
import com.app.micaihu.view.main.game.GameDownloadActivity;
import com.app.micaihu.view.main.mine.activity.BrowseHistoryActivity;
import com.app.micaihu.view.set.AliFeedBackActivity;
import com.app.micaihu.view.set.SetActivity;
import com.app.micaihu.view.user.userinfo.activity.AttentionAndFansSwitchPageActivity;
import com.app.micaihu.view.user.userinfo.activity.MyHomePageCollectionActicity;
import com.app.micaihu.view.user.userinfo.activity.MyHomepageDynamicActivity;
import com.app.micaihu.view.user.usertask.InvicodeActivity;
import com.app.micaihu.view.user.usertask.UserTaskActivity;
import com.app.utils.biz.Biz;
import com.app.utils.util.image.LoadImageUtils;
import com.app.utils.util.osutils.StatusBarUtils;
import com.app.utils.util.view.pulltozoom.OnMyScrollListener;
import com.app.utils.util.view.pulltozoom.PullToZoomScrollViewEx;
import com.baidu.mobstat.StatService;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ViewUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by Guo on 2016/10/10.
 * 我 页面的fragment
 */
public class MineFragment extends BaseFragment implements View.OnClickListener, OnMyScrollListener {
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_mine_page;
    }

    Activity mActivity;//当前依附的activity
    private ImageView civUserInforAvater;
    private TextView tvUserName;
    private TextView tvJungong;
    private TextView tvJunxiang;
    private TextView tvPrompt;
    private LinearLayout llToLogin;

    private LinearLayout llJunxian;
    private CustomImageView civRank2;
    private TextView tvRankName;
    private TextView tvTime;
    private View titleBg;
    private PullToZoomScrollViewEx ptzsv;

    private RecyclerView rvMenu;
    private ImageView ivSet;
    private MineMenuFragmentAdapter mineFragmentAdapter;
    private int exchangeCount;//点击兑换中心计数
    boolean isShowGame = AppConfigManager.getInstance().readConfig(ConfigKeyConstant.isGameShow, false);
    boolean isHonourMsg;

    //功能设置集合
    private ArrayList<MineSetList> setLists = new ArrayList<>();

    @Override
    protected void setData() {
        hideLoading();
        initList();
        initView();
        LiveEventBus.get(Config.EventBus.taskSuccess, Boolean.class).observe(this, new androidx.lifecycle.Observer<Boolean>() {
            @Override
            public void onChanged(@Nullable Boolean loginSuccess) {
                ViewUtils.runOnUiThreadDelayed(new Runnable() {
                    @Override
                    public void run() {
                        initUserInfor();
                    }
                }, 100);

            }
        });
    }

    @Override
    protected void addListeners() {
        civUserInforAvater.setOnClickListener(this);
        llToLogin.setOnClickListener(this);
        tvJungong.setOnClickListener(this);
        tvJunxiang.setOnClickListener(this);
        ivSet.setOnClickListener(this);
        ptzsv.setScrollListener(this);
    }

    @Override
    protected void lazyLoad() {

    }

    @Override
    public void onAttach(Activity activity) {
        this.mActivity = activity;
        super.onAttach(activity);
    }

    @Override
    public void onResume() {
        super.onResume();
        initUserInfor();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            initUserInfor();
        }
    }


    private void initList() {
        //初始化set 的数据
        if (setLists == null) {
            setLists = new ArrayList<>();
        }
        setLists.clear();

        MineSetList mineSetList1 = new MineSetList();
        mineSetList1.itemString = StringUtils.getString(R.string.userinfor_today_task);
        mineSetList1.itemDrawableId = R.drawable.user_list_fight;
        setLists.add(mineSetList1);


        MineSetList mineSetList2 = new MineSetList();
        mineSetList2.itemString = StringUtils.getString(R.string.userinfor_exchange);
        mineSetList2.itemDrawableId = R.drawable.user_list_exchange;
        setLists.add(mineSetList2);


        MineSetList mineSetList3 = new MineSetList();
        mineSetList3.itemString = StringUtils.getString(R.string.userinfor_history);
        mineSetList3.itemDrawableId = R.drawable.user_list_history;
        setLists.add(mineSetList3);

        if (isShowGame) {
            MineSetList mineSetList4 = new MineSetList();
            mineSetList4.itemString = StringUtils.getString(R.string.userinfor_mygame);
            mineSetList4.itemDrawableId = R.drawable.user_list_game;
            setLists.add(mineSetList4);
        }

        MineSetList mineSetList11 = new MineSetList();
        mineSetList11.itemString = StringUtils.getString(R.string.userinfor_honour);
        mineSetList11.itemDrawableId = R.drawable.user_list_honour;
        if (isHonourMsg) {
            mineSetList11.itemRedDot = 1;
        } else {
            mineSetList11.itemRedDot = 0;
        }
        setLists.add(mineSetList11);

        MineSetList mineSetList5 = new MineSetList();
        mineSetList5.itemString = StringUtils.getString(R.string.userinfor_mytopic);
        mineSetList5.itemDrawableId = R.drawable.user_list_topic;
        setLists.add(mineSetList5);


        MineSetList mineSetList6 = new MineSetList();
        mineSetList6.itemString = StringUtils.getString(R.string.userinfor_collection);
        mineSetList6.itemDrawableId = R.drawable.user_list_collect;
        setLists.add(mineSetList6);


        MineSetList mineSetList7 = new MineSetList();
        mineSetList7.itemString = StringUtils.getString(R.string.userinfor_myfollow);
        mineSetList7.itemDrawableId = R.drawable.user_list_concern;
        setLists.add(mineSetList7);


        MineSetList mineSetList8 = new MineSetList();
        mineSetList8.itemString = StringUtils.getString(R.string.set_yaoqingma);
        mineSetList8.itemDrawableId = R.drawable.user_list_code;

        if (UserInforManager.getInstance().isLogin()) {
            UserTask task = UserInforManager.getInstance().getUserInfor().getTask();
            if (task != null && task.getIsInvited()) {
                //已邀请
            } else {
                setLists.add(mineSetList8);
            }
        } else {
            setLists.add(mineSetList8);
        }

        MineSetList mineSetList9 = new MineSetList();
        mineSetList9.itemString = StringUtils.getString(R.string.set_permission);
        mineSetList9.itemDrawableId = R.drawable.user_list_permission;
        setLists.add(mineSetList9);

        MineSetList mineSetList10 = new MineSetList();
        mineSetList10.itemString = StringUtils.getString(R.string.set_yijian);
        mineSetList10.itemDrawableId = R.drawable.user_list_help;
        setLists.add(mineSetList10);
    }

    public void setHonourMsg(boolean msg) {
        isHonourMsg = msg;
        if (mineFragmentAdapter != null) {
            List<MineSetList> list = mineFragmentAdapter.getData();
            if (list != null) {
                for (MineSetList item : list) {
                    if (StringUtils.getString(R.string.userinfor_honour).equals(item.itemString)) {
                        if (msg) {
                            item.itemRedDot = 1;
                        } else {
                            item.itemRedDot = 0;
                        }
                    }
                }
                mineFragmentAdapter.notifyDataSetChanged();
            }
        }
    }

    /**
     * 初始化页面控件
     */
    private void initView() {
        ptzsv = getRootView().findViewById(R.id.ptzsv);
        //title
        titleBg = getRootView().findViewById(R.id.view_bg);
        titleBg.setVisibility(View.VISIBLE);
        titleBg.setOnClickListener(this);
        //header
        civUserInforAvater = getRootView().findViewById(R.id.civ_userinfor_avater);
        tvUserName = getRootView().findViewById(R.id.tv_name_or_login);
        tvJungong = getRootView().findViewById(R.id.tv_jungong);
        tvJunxiang = getRootView().findViewById(R.id.tv_junxiang);
        tvPrompt = getRootView().findViewById(R.id.tv_prompt);
        llToLogin = getRootView().findViewById(R.id.ll_tologin);

        ivSet = getRootView().findViewById(R.id.iv_set);

        StatusBarUtils.setTitleMargin(getRootView(), R.id.header_title);

        //2.0.1新增view
        llJunxian = getRootView().findViewById(R.id.ll_junxian);
        civRank2 = getRootView().findViewById(R.id.civ_rank);
        tvRankName = getRootView().findViewById(R.id.tv_rankname);
        tvTime = getRootView().findViewById(R.id.tv_time);

        rvMenu = getRootView().findViewById(R.id.rvMenu);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 4);
        rvMenu.setLayoutManager(gridLayoutManager);

        mineFragmentAdapter = new MineMenuFragmentAdapter(setLists);
        rvMenu.setAdapter(mineFragmentAdapter);
        mineFragmentAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                MineSetList item = mineFragmentAdapter.getItem(position);
                if (item == null) return;
                if (StringUtils.getString(R.string.userinfor_readmode).equals(item.getItemString())
                        || StringUtils.getString(R.string.userinfor_readmode_normal).equals(item.getItemString())) {
                    setReadmode();
                } else if (StringUtils.getString(R.string.userinfor_today_task).equals(item.getItemString())) {
                    startActivity(new Intent(mActivity, UserTaskActivity.class));
                    StatService.onEvent(mActivity, "052", "任务中心", 1);//统计事件的点击次数
                } else if (StringUtils.getString(R.string.userinfor_exchange).equals(item.getItemString())) {
                    if (UserInforManager.getInstance().isLogin()) {
                        exchangeCount++;
                        UserInforManager.getInstance().toWebActivity(mActivity, "", UserInforManager.getInstance().getUserInfor().getTask().getExchangeUrl());
                    } else {
                        UserInforManager.getInstance().toLoginPage(getActivity());
                    }
                } else if (StringUtils.getString(R.string.userinfor_history).equals(item.getItemString())) {
                    startActivity(new Intent(mActivity, BrowseHistoryActivity.class));
                } else if (StringUtils.getString(R.string.userinfor_mygame).equals(item.getItemString())) {
                    //跳转我的游戏
                    startActivity(new Intent(mActivity, GameDownloadActivity.class));
                    StatService.onEvent(mActivity, "007", "右上角我的游戏", 1);//统计事件的点击次数
                } else if (StringUtils.getString(R.string.userinfor_mytopic).equals(item.getItemString())) {
                    if (UserInforManager.getInstance().isLogin()) {
                        Intent intent = new Intent(mActivity, MyHomepageDynamicActivity.class);
                        intent.putExtra(Config.Extra.PARAMETER1, UserInforManager.getInstance().getUserInfor().getUid());
                        intent.putExtra(Config.Extra.PARAMETER2, true);
                        startActivity(intent);
                    } else {
                        UserInforManager.getInstance().toLoginPage(mActivity);
                    }
                } else if (StringUtils.getString(R.string.userinfor_collection).equals(item.getItemString())) {
                    startActivity(new Intent(mActivity, MyHomePageCollectionActicity.class));
                    StatService.onEvent(mActivity, "052", "我的收藏", 1);//统计事件的点击次数
                } else if (StringUtils.getString(R.string.userinfor_myfollow).equals(item.getItemString())) {
                    if (!UserInforManager.getInstance().isLogin()) {
                        UserInforManager.getInstance().toLoginPage(mActivity);
                        return;
                    }
                    Intent intentFollow = new Intent(mActivity, AttentionAndFansSwitchPageActivity.class);
                    intentFollow.putExtra(Config.Extra.PARAMETER1, "0");
                    intentFollow.putExtra(Config.Extra.PARAMETER2, UserInforManager.getInstance().getUserInfor().getUid());
                    startActivity(intentFollow);
                    StatService.onEvent(mActivity, "052", "我的关注", 1);//统计事件的点击次数
                } else if (StringUtils.getString(R.string.set_yaoqingma).equals(item.getItemString())) {
                    if (UserInforManager.getInstance().isLogin()) {
                        startActivityForResult(new Intent(mActivity, InvicodeActivity.class), 1);
                    } else {
                        UserInforManager.getInstance().toLoginPage(mActivity);
                    }
                } else if (StringUtils.getString(R.string.set_yijian).equals(item.getItemString())) {
                    startActivity(new Intent(mActivity, AliFeedBackActivity.class));
                    StatService.onEvent(mActivity, "052", "帮助和反馈", 1);//统计事件的点击次数
                } else if (StringUtils.getString(R.string.set_permission).equals(item.getItemString())) {
                    SharedPreferences sharedPreferences = AppConfigManager.getInstance().getConfigSP();
                    String url = sharedPreferences.getString(ConfigKeyConstant.agreementUrl, "");
                    if (!StringUtils.isEmpty(url)) {
                        UserInforManager.getInstance().toWebActivity(mActivity, "", url);
                    }
                } else if (StringUtils.getString(R.string.userinfor_honour).equals(item.getItemString())) {
                    if (UserInforManager.getInstance().isLogin()) {
                        Bundle bundle = new Bundle();
                        bundle.putString(Config.Extra.toUid, Biz.getInstance().uid());
                        enterPager(ArmyMedalListActivity.class, bundle);
                    } else {
                        UserInforManager.getInstance().toLoginPage(mActivity);
                    }
                }
            }
        });
    }

    /**
     * 设置页面数据
     */
    public void initUserInfor() {
        //判断是否登录
        if (!StringUtils.isEmpty(Biz.getInstance().uid())) {
            llJunxian.setVisibility(View.VISIBLE);
            tvPrompt.setVisibility(View.GONE);
            UserInfor userInfor = UserInforManager.getInstance().getUserInfor();
            UserTask task = null;
            if (userInfor != null) {
                ImageLoadUtils.loadCircleImage(userInfor.getHeadPic(), civUserInforAvater, R.drawable.task_head_nologging_nor);
                tvUserName.setText(userInfor.getNickName());
                tvTime.setText(userInfor.getMilitaryTime());
                task = userInfor.getTask();
            }
            if (task != null) {
                String string = "军功 " + "<font color=\"#ffdb0c\">" + task.getMilitaryExploit() + "</font>";
                tvJungong.setText(Html.fromHtml(string));
                string = "金币 " + "<font color=\"#ffdb0c\">" + task.getMilitarPay() + "</font>";
                tvRankName.setText(task.getRankName());
                tvJunxiang.setText(Html.fromHtml(string));
                LoadImageUtils.getInstance().loadImage(civRank2, task.getRankIcon());
            }
            UserInforManager.getInstance().showLevelDialog(mActivity);
        } else {//非登录状态
            llJunxian.setVisibility(View.GONE);
            tvPrompt.setVisibility(View.VISIBLE);
            tvUserName.setText(getResources().getString(R.string.user_tologin));
            ImageLoadUtils.loadCircleImage(R.drawable.task_head_nologging_nor, civUserInforAvater);
            tvJungong.setText(getResources().getString(R.string.user_militaryexploit));
            tvJunxiang.setText(getResources().getString(R.string.user_militarypay));
        }
        initList();
        if (mineFragmentAdapter != null) {
            mineFragmentAdapter.notifyDataSetChanged();
        }
        if (UserInforManager.getInstance().isLogin() && exchangeCount > 0) {
            exchangeCount = 0;
            UserInforManager.getInstance().getUserTask(getActivity(), false);
        }
        showExplainGuide();
    }


    @Override
    public void onClick(View v) {
        if (v == null) return;
        switch (v.getId()) {
            case R.id.view_bg:
                break;
            case R.id.ll_tologin://未登录点击
                if (!UserInforManager.getInstance().isLogin()) {
                    UserInforManager.getInstance().toLoginPage(mActivity);
                }
                break;
            case R.id.civ_userinfor_avater://头像点击
                if (UserInforManager.getInstance().isLogin()) {
                    MyHomepageDynamicActivity.goToUserHomePage(mActivity, Biz.getInstance().uid());
                    StatService.onEvent(mActivity, "052", "头像点击", 1);//统计事件的点击次数
                } else {
                    UserInforManager.getInstance().toLoginPage(mActivity);
                }
                break;
            case R.id.tv_jungong://去奖励详细页面
                if (UserInforManager.getInstance().isLogin()) {
                    UserInforManager.getInstance().toWebActivity(mActivity, "奖励规则", UserInforManager.getInstance().getUserInfor().getTask().getScoreUrl());
                }
                StatService.onEvent(mActivity, "052", "军功金币奖励明细", 1);//统计事件的点击次数
                break;
            case R.id.tv_junxiang://去奖励详细页面
                if (UserInforManager.getInstance().isLogin()) {
                    UserInforManager.getInstance().toWebActivity(mActivity, "奖励规则", UserInforManager.getInstance().getUserInfor().getTask().getGoldUrl());
                }
                StatService.onEvent(mActivity, "052", "军功金币奖励明细", 1);//统计事件的点击次数
                break;
            case R.id.iv_set://设置
                startActivity(new Intent(mActivity, SetActivity.class));
                StatService.onEvent(mActivity, "052", "设置", 1);//统计事件的点击次数
                break;
        }

    }

    /**
     * 切换夜间模式
     */
    private void setReadmode() {
        ArrayList<Object> parms = new ArrayList<>();
        parms.add(TypeConstant.HANDLER_TYPE_1);
        parms.add(true);//改变资源配置
        EventBus.getDefault().post(parms);
    }

    @Override
    public void onScroll(int scrollY) {
    }

    /**
     * 展示提示军衔功能
     */
    private void showExplainGuide() {
        if (AppConfigManager.getInstance().readConfig(ConfigKeyConstant.firstshow_exploit, false) || mActivity.isFinishing()) {
            return;
        }
        AppConfigManager.getInstance().writeConfig(ConfigKeyConstant.firstshow_exploit, true);
        ArrayList<Object> parms = new ArrayList<>();
        parms.add("3");
        EventBus.getDefault().post(parms);
    }


}
